package com.system.healthproject.model.sickuser.service.imp;

import com.system.healthproject.bean.DoctorInfo;
import com.system.healthproject.bean.PagesBean;
import com.system.healthproject.bean.ReactionParams;
import com.system.healthproject.common.ApiResult;
import com.system.healthproject.mapper.*;
import com.system.healthproject.model.admin.paramsbean.*;
import com.system.healthproject.model.sickuser.params.UserDoctorsItem;
import com.system.healthproject.model.sickuser.params.UserEditPatientParams;
import com.system.healthproject.model.sickuser.params.UserPatientInfo;
import com.system.healthproject.model.sickuser.params.UserRegisterPhone;
import com.system.healthproject.model.sickuser.service.SickUserServices;
import com.system.healthproject.pojo.*;
import com.system.healthproject.service.RoleService;
import com.system.healthproject.utils.JwtUtil;
import com.system.healthproject.utils.Md5Utils;
import com.system.healthproject.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SickUserServiceImp implements SickUserServices {

    @Autowired
    LoginMapper loginMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    RoleService roleService;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    FrequencyMapper frequencyMapper;
    @Autowired
    ReactionsMapper reactionsMapper;
    @Autowired
    DoctorMapper doctorMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    VisitRecordsMapper visitRecordsMapper;
    @Autowired
    SymptomMapper symptomMapper;
    @Autowired
    DiseaseOnsetMapper diseaseOnsetMapper;
    @Autowired
    AbnormalEEGMapper abnormalEEGMapper;
    @Autowired
    CtMapper ctMapper;
    @Autowired
    DrugMapper drugMapper;
    @Autowired
    OperationMapper operationMapper;
    @Autowired
    ChronicMapper chronicMapper;
    @Autowired
    InheritanceMapper inheritanceMapper;
    @Autowired
    NowHistoryMapper nowHistoryMapper;
    @Autowired
    BeforeHistoryMapper beforeHistoryMapper;
    @Autowired
    FamilyHistoryMapper familyHistoryMapper;
    @Autowired
    private TransactionMapper transactionMapper;
    @Autowired
    CardOrderMapper cardOrderMapper;

    @Override
    public String login(LoginParams loginParams) {
        loginParams.setPassword(Md5Utils.md5(loginParams.getPassword()));
        Map<String, Object> map = loginMapper.selectUserInfoByLoginParams(loginParams);
        if(map==null){
            return null;
        }
        if(!map.containsKey("loginPatientid")||map.get("loginPatientid")==null){
            return null;
        }
        Integer loginState = (Integer) map.get("loginState");
        if(loginState==2){
            return null;
        }
        Map<String, Object> hashMap = new HashMap<>();
        Integer login_id = (Integer) map.get("loginId");
        String phone = (String) map.get("loginPhone");
        String tokenKey = phone + login_id;
        String oldToken = (String) redisUtil.get(tokenKey);
        if(oldToken!=null){
            //删除原本的信息缓存
            redisUtil.del(oldToken);
        }
        hashMap.put("userId", login_id);
        hashMap.put("phone",map.get("loginPhone"));
        String timeToken = JwtUtil.createTimeToken(hashMap);
        boolean set = redisUtil.set(timeToken, map, 0);
        boolean set1 = redisUtil.set(tokenKey, timeToken, 0);
        if(set&&set1){
            return timeToken;
        }
        return null;
    }

    @Transactional
    @Override
    public Boolean register(UserRegisterPhone loginParams) {
        String code = loginParams.getCode();
        String username = loginParams.getUsername();
        String phoneKey = username + "code";
        String redisCode = (String) redisUtil.get(phoneKey);
        if(redisCode==null){
            return false;
        }
        if(!code.equals(redisCode)){
            return false;
        }
        Patient record = new Patient();
        record.setPatientSex(1);
        patientMapper.insertSelective(record);
        Integer patientId = record.getPatientId();
        Login record1 = new Login();
        record1.setLoginPhone(loginParams.getUsername());
        record1.setLoginPassword(Md5Utils.md5(loginParams.getPassword()));
        record1.setLoginPatientid(patientId);
        record1.setCreatetime(new Date());
        record1.setLoginState(1);
        record1.setLoginHeadimg("http://img1.imgtn.bdimg.com/it/u=1728577482,2585850803&fm=26&gp=0.jpg");
        loginMapper.insert(record1);
        Integer loginId = record1.getLoginId();
        Boolean aBoolean = roleService.addUserRole(loginId, 4);
        Account record2 = new Account();
        record2.setLoginId(loginId);
        record2.setVirtualmoney(0.0);
        accountMapper.insert(record2);
        return aBoolean;
    }

    @Override
    public Boolean addFrequency(int frequencyNumber, Integer loginId) {
        Frequency frequency = frequencyMapper.selectByUserId(loginId);
        int i=0;
        if(frequency!=null){
            frequency.setFrequencyNumber(frequencyNumber);
            frequency.setUpdatetime(new Date());
             i = frequencyMapper.updateByPrimaryKeySelective(frequency);
        }else {
            frequency=new Frequency();
            frequency.setCreatetime(new Date());
            frequency.setUpdatetime(new Date());
            frequency.setPatientId(loginId);
            frequency.setFrequencyNumber(frequencyNumber);
            i=frequencyMapper.insertSelective(frequency);
        }
        return i==1;
    }

    @Transactional
    @Override
    public ApiResult<Object> addReactions(ReactionParams reactionParams, Integer loginId) {
        int totalByNow = reactionsMapper.getTotalByNow(loginId);
        if(totalByNow==0){
            List<Integer> ids = reactionParams.getIds();
            for (Integer id : ids) {
                Reactions record = new Reactions();
                record.setCreatetime(new Date());
                record.setPatientId(loginId);
                record.setDictionariesId(id);
                reactionsMapper.insert(record);
            }
            return ApiResult.success("添加成功");
        }else {
            return ApiResult.failure("今日已提交症状,请勿重复添加");

        }
    }

    @Override
    public ApiResult bindDoctor(Integer loginId, Integer doctorId) {
        Patient patient = patientMapper.selectByLoginId(loginId);
        Integer doctorId1 = patient.getDoctorId();
        if(doctorId1==null){
            patient.setDoctorId(doctorId);
            patient.setBindTime(new Date());
            int i = patientMapper.updateByPrimaryKeySelective(patient);
            return ApiResult.withBoolean(i==1,"绑定医生成功","绑定医生失败");
        }else {
            if(doctorId1!=doctorId){
                patient.setDoctorId(doctorId);
                int i = patientMapper.updateByPrimaryKeySelective(patient);
                return ApiResult.withBoolean(i==1,"更换绑定医生成功","更换绑定医生失败");
            }
        }
        return new ApiResult(401,"已绑定");
    }

    @Override
    public DoctorInfo userGetDoctorInfoById(Integer loginId, Integer doctorId) {
        DoctorInfo doctorInfo = doctorMapper.selectDoctorByLoginId(doctorId);
        Patient patient = patientMapper.selectByLoginId(loginId);
        Integer doctorId1 = patient.getDoctorId();
        if(doctorId1!=null&&doctorId1==doctorId){
            doctorInfo.setBand(true);
        }else {
            doctorInfo.setBand(false);
        }
        return doctorInfo;
    }

    @Override
    public UserPatientInfo getPatientInfo(Integer loginId) {
        UserPatientInfo patientInfoByLoginId =
                patientMapper.getPatientInfoByLoginId(loginId);
        int recordSizeByLoginId = recordMapper.getRecordSizeByLoginId(loginId);
        patientInfoByLoginId.setInfo(recordSizeByLoginId>0);
        return patientInfoByLoginId;
    }

    @Override
    public List<FrequencyParams> userGetFrequencyList(Integer loginId, int type) {
        List<FrequencyParams> diseaseLogListByDay=null;
        if(type==1){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByDay(loginId);
        }else if(type==2){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByWeek(loginId);
        }else if(type==3){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByMonth(loginId);
        }
        return diseaseLogListByDay;
    }

    @Override
    public List<ReactionsParams> userGetReactions(Integer loginId, int type) {
        List<ReactionsParams> reactionsByWeek=null;
        if(type==2){
            reactionsByWeek = reactionsMapper.getReactionsByWeek(loginId);
        }else if(type==3){
            reactionsByWeek = reactionsMapper.getReactionsByMonth(loginId);
        }else if(type==1){
            reactionsByWeek = reactionsMapper.getReactionsByDay(loginId);
        }
        return reactionsByWeek;
    }

    @Override
    public PagesBean<VisitRecordsShowParams> userGetVisitRecordsList(int page, int size, Integer loginId) {
        PagesBean<VisitRecordsShowParams> visitRecordsShowParamsPagesBean = new PagesBean<>();
        List<VisitRecordsShowParams> visitRecordsShowParams =
                visitRecordsMapper.selectList((page-1)*size, size, loginId);
        int totalByUserId = visitRecordsMapper.getTotalByUserId(loginId);
        visitRecordsShowParamsPagesBean.setData(visitRecordsShowParams);
        visitRecordsShowParamsPagesBean.setNowsPage(page);
        visitRecordsShowParamsPagesBean.setPageSize(size);
        visitRecordsShowParamsPagesBean.setDataCount(totalByUserId);
        return visitRecordsShowParamsPagesBean;
    }

    @Override
    public RecordInfoParams userGetRecordInfo(Integer loginId, int recordId) {
        RecordInfoParams recordInfoParams = new RecordInfoParams();
        Record recordInfoByUserId = recordMapper.getRecordInfo(loginId,recordId);
        if(recordInfoByUserId==null){
            return null;
        }
        Integer nowhistoryId = recordInfoByUserId.getNowhistoryId();

        NowHistory nowHistory = nowHistoryMapper.selectByPrimaryKey(nowhistoryId);
        Integer diagnosisState = nowHistory.getDiagnosisState();//诊断状态（1 是   2否）
        recordInfoParams.setDiagnosis_state(diagnosisState);
        if(diagnosisState==1){
            List<Symptom> symptoms = symptomMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setSymptoms(symptoms);
            List<DiseaseOnset> diseaseOnsets = diseaseOnsetMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setDiseaseOnsets(diseaseOnsets);
        }
        Integer encephlogramState = nowHistory.getEncephlogramState();//（1 正常  2异常）
        recordInfoParams.setEncephlogram_state(encephlogramState);
        if(encephlogramState==2){
            List<AbnormalEEG> abnormalEEGS = abnormalEEGMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setAbnormalEEGS(abnormalEEGS);
        }
        Integer ctState = nowHistory.getCtState();//核磁/CT状态（1 正常  2异常）
        recordInfoParams.setCt_state(ctState);
        if(ctState==2){
            List<Ct> ctList = ctMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setCts(ctList);
        }
        Integer geneState = nowHistory.getGeneState();//基因状态
        recordInfoParams.setGeneState(geneState);
        Integer attacksNumber = nowHistory.getAttacksNumber();//发作次数
        recordInfoParams.setAttacks_number(attacksNumber);
        Integer attacksFrequency = nowHistory.getAttacksFrequency();
        recordInfoParams.setAttacks_frequency(attacksFrequency);//发作频率（1 日 2周 3月）
        Integer medicationState = nowHistory.getMedicationState();//药物治疗状态（ 1 是 2否）
        recordInfoParams.setMedication_state(medicationState);
        if(medicationState==1){
            List<Drug> drugs = drugMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setMedicationDrugList(drugs);
        }
        Integer operationState = nowHistory.getOperationState();//是否手术状态（1 是 2否）
        recordInfoParams.setOperation_state(operationState);
        if(operationState==1){
            List<Operation> operations = operationMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setOperationsList(operations);
        }
        Integer hormoneState = nowHistory.getHormoneState();//甲强激素治疗状态（1 是  2否）
        recordInfoParams.setHormone_state(hormoneState);
        Integer immuneState = nowHistory.getImmuneState();//免疫治疗状态（1 是 2否）
        recordInfoParams.setImmune_state(immuneState);
        Integer ketogenicState = nowHistory.getKetogenicState();//生酮饮食状态（1 是 2否）
        recordInfoParams.setKetogenic_state(ketogenicState);
        Integer otherState = nowHistory.getOtherState();//现病史其他状态（1 是  2否）
        recordInfoParams.setOther_state(otherState);

        Integer beforehistoryId = recordInfoByUserId.getBeforehistoryId();
        BeforeHistory beforeHistory = beforeHistoryMapper.selectByPrimaryKey(beforehistoryId);
        Integer drugallergyState = beforeHistory.getDrugallergyState();//是否药物过敏（1 是    2 否）
        recordInfoParams.setDrugAllergy_state(drugallergyState);
        if(drugallergyState==1){
            List<Drug> drugs = drugMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setBeforeDrugList(drugs);
        }
        Integer traumaState = beforeHistory.getTraumaState();//是否有外伤史（1.是   2.否）
        recordInfoParams.setTrauma_state(traumaState);
        if(traumaState==1){
            String traumaContent = beforeHistory.getTraumaContent();
            recordInfoParams.setTrauma_content(traumaContent);
        }
        Integer chronicState = beforeHistory.getChronicState();//慢病史状态（1 是   2 否）
        recordInfoParams.setChronic_state(chronicState);
        if(chronicState==1){
            List<Chronic> chronics = chronicMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setChronics(chronics);
        }
        Integer injuryState = beforeHistory.getInjuryState();//产伤状态（1 是   2 否）
        recordInfoParams.setInjury_state(injuryState);
        Integer infectedState = beforeHistory.getInfectedState();//是否感染（1 是   2 否）
        recordInfoParams.setInfected_state(infectedState);
        Integer hemorrhageState = beforeHistory.getHemorrhageState();//出血（1 是   2 否）
        recordInfoParams.setHemorrhage_state(hemorrhageState);
        Integer convulsionsState = beforeHistory.getConvulsionsState();//是否高热惊厥史（1 是   2 否）
        recordInfoParams.setConvulsions_state(convulsionsState);

        Integer familyhistoryId = recordInfoByUserId.getFamilyhistoryId();
        FamilyHistory familyHistory = familyHistoryMapper.selectByPrimaryKey(familyhistoryId);
        Integer inheritanceState = familyHistory.getInheritanceState();
        recordInfoParams.setInheritance_state(inheritanceState);
        if(inheritanceState==1){
            List<Inheritance> inheritances = inheritanceMapper.selectListByFimilyHis(familyhistoryId);
            recordInfoParams.setInheritances(inheritances);
        }
        Integer marryState = familyHistory.getMarryState();
        recordInfoParams.setMarry_state(marryState);
        Integer birthState = familyHistory.getBirthState();
        recordInfoParams.setBirth_state(birthState);
        return recordInfoParams;
    }

    @Override
    public List<UserDoctorsItem> userGetDoctorsList(Integer loginId, Integer isFollow) {
        Integer integer = loginMapper.selectPatientIdByLoginId(loginId);
        List<UserDoctorsItem> userDoctorsItems = doctorMapper.doctorsList(integer,isFollow);
        return userDoctorsItems;
    }

    @Override
    public boolean userFollowDoctor(Integer loginId, Integer doctorId) {
        Integer integer = loginMapper.selectPatientIdByLoginId(loginId);
        int i = doctorMapper.userFollowDoctor(integer, doctorId,new Date());
        return i==1;
    }

    @Transactional
    @Override
    public boolean userEditPatient(UserEditPatientParams patientDoctor, Integer loginId) {
        Login login = loginMapper.selectByPrimaryKey(loginId);
        String headImg = patientDoctor.getHeadImg();
        if(headImg !=null){
            login.setLoginHeadimg(headImg);
            loginMapper.updateByPrimaryKeySelective(login);
        }
        Patient patient = patientMapper.selectByLoginId(loginId);
        String patientNick = patientDoctor.getPatientNick();
        Integer patientSex = patientDoctor.getPatientSex();
        Date patientBirthday = patientDoctor.getPatientBirthday();
        Integer illage = patientDoctor.getIllage();
        Integer province = patientDoctor.getProvince();
        Integer city = patientDoctor.getCity();
        if(patientNick!=null){
            patient.setPatientNick(patientNick);
        }
        if(patientSex!=null){
            patient.setPatientSex(patientSex);
        }
        if(patientBirthday!=null){
            patient.setPatientBirthday(patientBirthday);
        }
        if(illage!=null){
            patient.setIllage(illage);
        }
        if(province!=null){
            patient.setProvince(province);
        }
        if(city!=null){
            patient.setCity(city);
        }
        int i = patientMapper.updateByPrimaryKeySelective(patient);
        return  i==1;
    }

    @Override
    public PatientInfo userPatientInfo(Integer loginId) {
        PatientInfo map = patientMapper.patientInfoByLoginId(loginId);
        return map;
    }


    /**
     * 充值成功 产生交易明细记录
     * @param orderId
     * @param time
     * @param money
     * @return
     */
    @Override
    @Transactional
    public Integer addTransaction(String orderId, String time, String money) {
        Integer cardId=Integer.parseInt(orderId);
        Integer loginId = cardOrderMapper.selectLoginId(orderId);//获取登录ID
        Date date = null;
        try {
             date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Double moneyNum = Double.parseDouble(money);
        Transaction transaction = new Transaction();
        transaction.setLoginId(loginId);
        transaction.setTransactionType("充值会员");
        transaction.setTransactionVirtualmoney(0.0);
        transaction.setTransactionTime(date);
        transaction.setTransactionState(1);
        transaction.setCollectionLoginid(0);
        transaction.setTransactionStatuetype(1);
        cardOrderMapper.updateStaute(orderId);
        return transactionMapper.addTransaction(transaction);
    }

    @Override
    public Double selectMoney(String orderNo) {
        return cardOrderMapper.selectMoney(Integer.parseInt(orderNo));
    }
}
